package com.sls.game.component;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.ServerDateAndTime;
import com.sls.game.common.DeductionRefund;
import com.sls.game.dao.GoodsOrderDAO;
import com.sls.game.pojo.DeductionRefundInfo;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.GoodsSupplyManageInfo;
import com.sls.game.pojo.SLSHttpInterfaceInfo;
import com.sls.game.service.impl.SLSHttpInterfaceServiceImpl;

@Component("sLSHttpInterfaceCom")
public class SLSHttpInterfaceComponentImpl extends SLSHttpInterfaceServiceImpl
		implements SLSHttpInterfaceComponent {

	private static Logger log = Logger
			.getLogger(SLSHttpInterfaceComponentImpl.class);

	private Gson gson = null;

	public SLSHttpInterfaceComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Resource(name = "goodsOrderDAO")
	private GoodsOrderDAO goodsOrderDAO;

	// @Resource(name="sLSHttpInterfaceService")
	// private SLSHttpInterfaceService sLSHttpInterfaceServices;

	public String insertOfTrading(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("请求ID：" + head.getRequestId()
					+ "，进入insertOfTrading方法，开始处理直充交易请求");
		}
		SLSHttpInterfaceInfo info = gson.fromJson(body,
				SLSHttpInterfaceInfo.class);
		boolean flag = checkDataOfInsertOfTrading(info, head.getRequestId());
		if (flag) { // 数据校验通过
			// 商品Id
			String goodsId = info.getGoodsId();
			// ***** 获取订单编号 *****
			String orderId = null;
			orderId = getSlsOrderNo();
			// 最终购买用户IP地址【暂时模拟最终购买用户IP】
			String merchantIP = "";
			if (StringUtils.isNotEmpty(info.getMerchantIP())) {
				merchantIP = info.getMerchantIP();
			} else {
				merchantIP = generateDycIp();
			}

			// ***** 下游用户身份校验 *****
			String userNo = info.getUserNo();
			String userIP = info.getClientIp(); // 下游用户IP
			String result = checkIdentity(userNo, userIP, false); // 绑定IP，第三个参数为true；不绑定IP，第三个参数为false
			if ("104".equals(result)) { // 合作方用户不存在
				String resultBody = null;
				resultBody = returnUserNotExist();
				return resultBody;
			} else if ("105".equals(result)) {
				SLSHttpInterfaceInfo sLSHttpInterfaceInfo = new SLSHttpInterfaceInfo();
				sLSHttpInterfaceInfo.setResMsg("FAILED");
				sLSHttpInterfaceInfo.setFailedCode("105");
				sLSHttpInterfaceInfo.setFailedReason("绑定的IP地址不匹配");
				String resultBody = null;
				resultBody = gson.toJson(sLSHttpInterfaceInfo);
				return resultBody;

			} else { // 身份校验通过
				GoodsSupplyManageInfo goodsSupplyManageInfo = null;
				// 去供货表查询供货商品
				goodsSupplyManageInfo = checkSupplyGoods(goodsId, head);
				if (goodsSupplyManageInfo != null) {
					// ***** 判断能否进行交易 *****
					boolean tradeFlag = judgmentCanTrading(info, head,
							goodsSupplyManageInfo);
					if (tradeFlag) { // 可以进行交易

						// 检查下游所传的订单总价是否正确
						boolean totalPriceFlag = checkTotalPrice(info,
								goodsSupplyManageInfo);
						if (totalPriceFlag) {
							// 写订单前，先判断该用户下订单是否重复提交
							GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
							goodsOrderInfo.setMerchantOrderId(info
									.getPtOrderNo());
							goodsOrderInfo.setContractId(info.getUserNo());
							String id = null;
							id = goodsOrderDAO
									.queryOrderIsExtisOfUserNo(goodsOrderInfo);
							if (id == null) { // 可以写订单
								// 订单时间戳
								String orderTime = ServerDateAndTime
										.getNowDateTimeOfFormat();
								// 向订单表写记录
								insertIntoGoodsOrder(info,
										goodsSupplyManageInfo, head, orderId,
										orderTime, merchantIP);

								// ************** 调用支付接口 ***************
								orderTime = orderTime.replace("-", "")
										.replace(":", "").replace(" ", "");
								String paymentStatus = ""; // 支付状态
								String paymentOrderNo = ""; // 支付交易单号
								DeductionRefundInfo deReFunInfo = null;
								try {
									deReFunInfo = DeductionRefund
											.invokeDeductRefund(info, orderId,
													"0", orderTime, "", head,
													goodsOrderDAO);
								} catch (Exception e) {
									log.error("请求ID：" + head.getRequestId()
											+ "，调用支付接口出现异常", e);
								}

								if (deReFunInfo != null) {
									paymentStatus = deReFunInfo
											.getPaymentStatus();
									paymentOrderNo = deReFunInfo.getTradeNo();
								}
								if ("1".equals(paymentStatus)) { // 支付成功
									String resultBody = null;
									try {
										// 支付成功时的操作
										resultBody = operatePaySuccess(
												orderTime, paymentOrderNo,
												orderId, head,
												goodsSupplyManageInfo, info,
												false, merchantIP);
									} catch (Exception e) {
										log.error("请求ID：" + head.getRequestId()
												+ "，调用上游接口出现异常", e);
									}
									return resultBody;
								} else if ("2".equals(paymentStatus)) { // 支付失败
									String resultBody = null;
									// 支付失败时的操作
									try {
										resultBody = operatePayFailure(
												orderTime, paymentOrderNo,
												orderId, head, info);
									} catch (Exception e) {
										log.error("请求ID：" + head.getRequestId()
												+ "，支付失败时更新订单异常！", e);
									}
									return resultBody;
								} else if ("4".equals(paymentStatus)) { // 充销
									// ...
								}
							} else { // 订单重复提交
								String resultBody = null;
								resultBody = submitOrderRepeat();
								return resultBody;
							}
						} else { // 下游用户提交的订单金额不正确
							SLSHttpInterfaceInfo sLSHttpInterfaceInfo = new SLSHttpInterfaceInfo();
							sLSHttpInterfaceInfo.setResMsg("FAILED");
							sLSHttpInterfaceInfo.setFailedCode("504");
							sLSHttpInterfaceInfo.setFailedReason("该笔订单总金额不正确");
							String resultBody = null;
							resultBody = gson.toJson(sLSHttpInterfaceInfo);
							return resultBody;
						}

					} else {
						SLSHttpInterfaceInfo sLSHttpInterfaceInfo = new SLSHttpInterfaceInfo();
						sLSHttpInterfaceInfo.setResMsg("FAILED");
						sLSHttpInterfaceInfo.setFailedCode("503");
						sLSHttpInterfaceInfo.setFailedReason("售价低于进价");
						String resultBody = null;
						resultBody = gson.toJson(sLSHttpInterfaceInfo);
						return resultBody;
					}
				} else { // 检查库存不足
					String resultBody = null;
					resultBody = checkReserveShortage();
					return resultBody;
				}
			}
		}
		return null;
	}

}
